package com.bankcomm.ui.views;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import com.bankcomm.R;
import com.bankcomm.common.LPMid;
import com.bankcomm.ui.BOCMainHome;
/**
 * 自定义拖动gridView
 * 
 * @date 2013-5-7
 */
public class DropDragGrid extends GridView {

	private int dragPosition;
	private int dropPosition;
	private int holdPosition;
	private int startPosition;
	private int specialPosition = -1;
	private int leftBottomPosition = -1;

	private int nColumns = 4;
	private int nRows;
	private int Remainder;

	private int itemTotalCount;
	private int halfItemWidth;

	private ImageView dragImageView = null;
	private ViewGroup dragItemView = null;

	private WindowManager windowManager = null;
	private WindowManager.LayoutParams windowParams = null;

	public int mLastX, xtox;
	public int mLastY, ytoy;
	private int specialItemY;
	private int leftBtmItemY;

	private String LastAnimationID;

	private boolean isCountXY = false;
	private boolean isMoving = false;

	public boolean isHome = false;

	// public Object temp = null;
	/**
	 * 是否拖动
	 * */
	public boolean canDragParm = true;
	public int topY = 0;
	private Rect mTouchFrame;
	/**
	 * 限制前三个图标是不能移动和删除的
	 * */
	private int limit = 0;
	private long lasttime;
	private DropGridAdapter adapter;
	private BOCMainHome mainHome;

	public DropDragGrid(Context context, boolean isHome) {
		super(context);

		mainHome = (BOCMainHome) context;
		this.isHome = isHome;
		this.setGravity(Gravity.CENTER_HORIZONTAL);
		this.setBackgroundDrawable(null);
		this.setVerticalScrollBarEnabled(false);
		this.setSelector(R.drawable.grid_item_bg);
		this.setNumColumns(4);
		this.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
				LayoutParams.FILL_PARENT));
	}

	boolean flag = false;

	public void setLongFlag(boolean temp) {
		flag = temp;
	}

	public boolean setOnItemLongClickListener(final MotionEvent ev) {
		this.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View view,
					int position, long arg3) {
				topY = 0;
				if (canDragParm) {
					if (null == adapter) {
						adapter = (DropGridAdapter) DropDragGrid.this
								.getAdapter();
					}
					// 标记为是我的首页
					if (isHome) {
						// 未登陆不进入编辑状态
						if (!LPMid.getInstance().um_.data.isLogin) {
							mainHome.showToast("不可操作，请登录后再做相应操作！");
							return true;
						}

						limit = LPMid.getInstance().um_.data.remommendSize;
						// 前三个和最后一个是不能移动的
						if ((limit > 0 && position <= (limit - 1))
								|| position == adapter.lstDate.size() - 1) {
							return true;
						}
						// 九宫格进入编辑状态
						if (!DropGridAdapter.isInEdit) {
							BCMHomeView.changeTitleView(true);
							adapter.stepIntoEditMode(true);
							return true;
							// 当处于拖动模式时viewflow禁止左右滑动
							// BCMHomeView.setScroll(false);
						}
					}

					int x = (int) ev.getX();
					int y = (int) ev.getY();
					mLastX = x;
					mLastY = y;
					startPosition = dragPosition = dropPosition = position;
					if (dragPosition == AdapterView.INVALID_POSITION) {

					}
					ViewGroup itemView = (ViewGroup) getChildAt(dragPosition
							- getFirstVisiblePosition());
					if (!isCountXY) {
						halfItemWidth = itemView.getWidth() / 2;
						int rows;
						itemTotalCount = getCount();
						rows = itemTotalCount / nColumns;
						Remainder = itemTotalCount % nColumns;
						nRows = Remainder == 0 ? rows : rows + 1;
						specialPosition = itemTotalCount - 1 - Remainder;
						if (Remainder != 1)
							leftBottomPosition = nColumns * (nRows - 1);
						if (Remainder == 0 || nRows == 1)
							specialPosition = 1;
						isCountXY = true;
					}

					View spcialItem = null;
					if (specialPosition != dragPosition && dragPosition != -1) {
						spcialItem = getChildAt(specialPosition);
					}
					specialItemY = spcialItem == null ? -1 : spcialItem
							.getTop();
					dragItemView = itemView;
					itemView.destroyDrawingCache();
					itemView.setDrawingCacheEnabled(true);
					// 设置背景色
					// itemView.setDrawingCacheBackgroundColor(0x000000);
					Bitmap bm = Bitmap.createBitmap(itemView
							.getDrawingCache(true));
					bm = Bitmap.createScaledBitmap(bm,
							dragItemView.getMeasuredWidth() + 10,
							dragItemView.getMeasuredHeight() + 10, false);
					Bitmap bitmap = Bitmap.createBitmap(bm, 0, 0,
							bm.getWidth(), bm.getHeight());

					startDrag(bitmap, x, y);
					hideDropItem();
					itemView.setVisibility(View.INVISIBLE);
					isMoving = false;
					return false;
				} else {
					return true;
				}
			};
		});

		return super.onInterceptTouchEvent(ev);
	}

	public void GetItemShadow(int x, int y) {

	}

	@Override
	public boolean onInterceptTouchEvent(MotionEvent ev) {
		if (ev.getAction() == MotionEvent.ACTION_DOWN) {
			long first = System.currentTimeMillis();
			/*
			 * 如果两次时间差值小于500毫秒,则对第二次点击事件无响应， 降低重复提交的概率(前台无法完全避免，最好由服务器来做) add by
			 * cheng.l
			 */
			if (lasttime > 0 && first - lasttime < 500) {
				lasttime = 0;
				return true;
			}
			lasttime = System.currentTimeMillis();
			return setOnItemLongClickListener(ev);
		}
		return super.onInterceptTouchEvent(ev);
	}

	@Override
	public boolean onTouchEvent(MotionEvent ev) {
		if (canDragParm) {
			if (dragImageView != null
					&& dragPosition != AdapterView.INVALID_POSITION) {
				int x = (int) ev.getX();
				int y = (int) ev.getY();
				switch (ev.getAction()) {
				case MotionEvent.ACTION_MOVE:
					if (!isCountXY) {
						xtox = x - mLastX;
						ytoy = y - mLastY;
						isCountXY = true;
					}
					onDrag(x, y);
					if (!isMoving)
						OnMove(x, y);
					break;
				case MotionEvent.ACTION_UP:
					stopDrag();
					onDrop(x, y);
					break;
				}
			}
		} 
		return super.onTouchEvent(ev);
	}

	/**
	 * 判断是否是点击的GridView空白处还是其ItemView上
	 * */
	public boolean pointChild(int x, int y) {
		Rect frame = mTouchFrame;
		if (frame == null) {
			mTouchFrame = new Rect();
			frame = mTouchFrame;
		}

		final int count = getChildCount();
		for (int i = count - 1; i >= 0; i--) {
			final View child = getChildAt(i);
			if (child.getVisibility() == View.VISIBLE) {
				child.getHitRect(frame);
				if (frame.contains(x, y)) {
					return true;
				}
			}
		}
		return false;
	}

	private void startDrag(Bitmap bm, int x, int y) {
		stopDrag();
		windowParams = new WindowManager.LayoutParams();
		windowParams.gravity = Gravity.TOP | Gravity.LEFT;
		int[] location = new int[2];
		dragItemView.getLocationOnScreen(location);
		windowParams.x = location[0];
		// 弹起时View的位置
		windowParams.y = location[1] - dragItemView.getHeight() / 2;

		windowParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
		windowParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
		windowParams.alpha = 0.8f;
		windowParams.format = PixelFormat.RGBA_8888;

		ImageView iv = new ImageView(getContext());
		iv.setImageBitmap(bm);
		windowManager = (WindowManager) getContext().getSystemService(
				Context.WINDOW_SERVICE);
		windowManager.addView(iv, windowParams);

		dragImageView = iv;
	}

	/**
	 * 移动view
	 * */
	public void OnMove(int x, int y) {
		int TempPosition = pointToPosition(x, y);
		int sOffsetY = specialItemY == -1 ? y - mLastY : y - specialItemY
				- halfItemWidth;
		int lOffsetY = leftBtmItemY == -1 ? y - mLastY : y - leftBtmItemY
				- halfItemWidth;
		if (TempPosition != AdapterView.INVALID_POSITION
				&& TempPosition != dragPosition) {
			dropPosition = TempPosition;
		} else if (specialPosition != -1 && dragPosition == specialPosition
				&& sOffsetY >= halfItemWidth) {
			dropPosition = (itemTotalCount - 1);
		} else if (leftBottomPosition != -1
				&& dragPosition == leftBottomPosition
				&& lOffsetY >= halfItemWidth) {
			dropPosition = (itemTotalCount - 1);
		}
		if (dragPosition != startPosition)
			dragPosition = startPosition;
		int MoveNum = dropPosition - dragPosition;
		if (dragPosition != startPosition && dragPosition == dropPosition)
			MoveNum = 0;

		/**
		 * "我的首页"频道,前三个item是不能移动，也不能被移动的
		 * */
		if (isHome) {
			if ((limit > 0 && dropPosition <= (limit - 1))
					|| dropPosition == (adapter.getCount() - 1)) {
				MoveNum = 0;
			}
		}

		if (MoveNum != 0) {
			int itemMoveNum = Math.abs(MoveNum);
			float Xoffset, Yoffset;
			for (int i = 0; i < itemMoveNum; i++) {
				if (MoveNum > 0) {
					holdPosition = dragPosition + 1;
					Xoffset = (dragPosition / nColumns == holdPosition
							/ nColumns) ? (-1) : (nColumns - 1);
					Yoffset = (dragPosition / nColumns == holdPosition
							/ nColumns) ? 0 : (-1);
				} else {
					holdPosition = dragPosition - 1;
					Xoffset = (dragPosition / nColumns == holdPosition
							/ nColumns) ? 1 : (-(nColumns - 1));
					Yoffset = (dragPosition / nColumns == holdPosition
							/ nColumns) ? 0 : 1;
				}
				ViewGroup moveView = (ViewGroup) getChildAt(holdPosition
						- getFirstVisiblePosition());
				Animation animation = getMoveAnimation(Xoffset, Yoffset);
				if (null != moveView) {
					moveView.startAnimation(animation);
				}
				dragPosition = holdPosition;
				if (dragPosition == dropPosition)
					LastAnimationID = animation.toString();
				animation
						.setAnimationListener(new Animation.AnimationListener() {
							@Override
							public void onAnimationStart(Animation animation) {
								// TODO Auto-generated method stub
								isMoving = true;
							}

							@Override
							public void onAnimationRepeat(Animation animation) {
								// TODO Auto-generated method stub
							}

							@Override
							public void onAnimationEnd(Animation animation) {
								// TODO Auto-generated method stub
								String animaionID = animation.toString();
								if (animaionID
										.equalsIgnoreCase(LastAnimationID)) {
									adapter.exchange(startPosition,
											dropPosition);
									startPosition = dropPosition;
									isMoving = false;
								}
							}
						});
			}
		}
	}

	private void onDrop(int x, int y) {
		// 当拖动结束时viewflow允许左右滑动
		// BCMHomeView.setScroll(true);
		adapter.showDropItem(true);
		adapter.notifyDataSetChanged();
	}

	/**
	 * 重新将移动后的九宫格位置保存到本地
	 * 
	 * @param adapter
	 * */
	// @SuppressWarnings("unchecked")
	// public void writeJsonStr(DropGridAdapter adapter) {
	// String channels = "";
	// for (int i = 0; i < adapter.getCount(); i++) {
	// Map<String,Object> item = (Map<String, Object>)adapter.getItem(i);
	//
	// String shortCut = item.get("id").toString();
	// String name="";
	// if(null != item.get("name")){
	// name = item.get("name").toString();
	// }
	// String url="";
	// if(null != item.get("url")){
	// url = item.get("url").toString();
	// }
	//
	// channels=channels.concat("{'id':"+"'"+shortCut+"',"+"'name':"+"'"+name+"',"
	// +"'url':"+"'"+url+"'},");
	// }
	// String json="{'channels':["+channels.substring(0,
	// channels.length()-1)+"]}";
	// Utils.printOutToConsole(json);
	// }

	/**
	 * 拖动view
	 * 
	 * @param int x
	 * @param int y
	 * */
	private void onDrag(int x, int y) {
		if (dragImageView != null) {
			if (topY <= 0) {
				int[] location = new int[2];
				this.getLocationOnScreen(location);
				topY = location[1] - BCMHomeView.getTabHeight();
			}
			windowParams.alpha = 0.8f;
			int left = dragImageView.getLeft() + x;
			int top = dragImageView.getTop() + y + topY
					- BCMHomeView.getTabHeight();

			windowParams.x = left - dragImageView.getWidth() / 2;
			// 计算并限制弹起的view可移动的高度，否则y轴上移动范围太大
			windowParams.y = top <= topY ? topY : top;
			windowManager.updateViewLayout(dragImageView, windowParams);
		}
	}

	private void stopDrag() {
		if (dragImageView != null) {
			windowManager.removeView(dragImageView);
			dragImageView = null;

		}
	}

	private void hideDropItem() {
		final DropGridAdapter adapter = (DropGridAdapter) this.getAdapter();
		adapter.showDropItem(false);
	}

	public Animation getMoveAnimation(float x, float y) {
		TranslateAnimation go = new TranslateAnimation(
				Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, x,
				Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, y);
		go.setFillAfter(true);
		go.setDuration(300);
		return go;
	}
}
